#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: 
@time: 2024/5/29 9:19 PM
@Function: 请输入模块功能描述
"""
import logging, os, time, colorlog
from config.setting import FILE_PATH
from logging.handlers import RotatingFileHandler  # 按文件大小滚动备份

logs_path = FILE_PATH['logs']
if not os.path.exists(logs_path):
    os.mkdir(logs_path)

log_file = os.path.join(logs_path, 'test.{}.log'.format(time.strftime('%Y_%m_%d_%H_%M_%S')))
print(log_file)


class HandleLogs:

    @classmethod
    def setting_log_color(cls):
        log_color_config = {
            'DEBUG': 'cyan',
            'INFO': 'green',
            'ERROR': 'red',
            'WARNING': 'yellow',
            'CRITICAL': 'red'
        }
        formatter = colorlog.ColoredFormatter(
            '%(log_color)s %(levelname)s - %(asctime)s - %(filename)s:%(lineno)d - [%(module)s:%(funcName)s] - %(message)s',
            log_colors = log_color_config)
        return formatter

    @classmethod
    def clear_logs_files(cls, log_folder_path):
        """
        删除logs文件夹下的所有内容
        """
        try:
            for log_files_name in os.listdir(log_folder_path):
                log_file_path = os.path.join(log_folder_path, log_files_name)
                if os.path.isfile(log_file_path):
                    os.remove(log_file_path)
        except Exception as e:
            print(f"clear_logs_files方法存在异常，请检查={e}")
        return 'clear logs success'

    @classmethod
    def out_print_logs(cls):
        cls.clear_logs_files(logs_path)
        logger = logging.getLogger(__name__)
        steam_format = cls.setting_log_color()
        # 防止重复打印日志
        if not logger.handlers:
            logger.setLevel(logging.DEBUG)
            log_format = logging.Formatter(
                '%(levelname)s - %(asctime)s - %(filename)s:%(lineno)d - [%(module)s:%(funcName)s] - '
                '%(message)s')
            # 把日志信息输出到控制台
            sh = logging.StreamHandler()
            sh.setLevel(logging.DEBUG)
            sh.setFormatter(steam_format)
            logger.addHandler(sh)

            # 把日志输出到文件里面
            fh = RotatingFileHandler(filename = log_file, mode = 'a', maxBytes = 5242880, backupCount = 7,
                                     encoding = 'utf-8')
            fh.setLevel(logging.DEBUG)
            fh.setFormatter(log_format)
            logger.addHandler(fh)

        return logger


logs = HandleLogs().out_print_logs()
# clear_logs = HandleLogs().clear_logs_files(logs_path)
# logs.info('这是info的日志')
# logs.error('这是错误日志信息')
# logs.debug('这是debug日志信息')
# logs.warning('这是警告日志信息')
# logs.critical('这是严重的日志信息')
